﻿using System.Collections.Generic;
using System.IO;
using System.Text;

namespace DbBuilder
{
	public class CsvTable : List<List<string>>
	{
		public readonly List<string> Header;

		public CsvTable(string fileName)
		{
			StreamReader reader = File.OpenText(fileName);
			StringBuilder item = new StringBuilder();
			List<string> row = new List<string>();
			bool escaped = false;
			bool header = true;
			while (!reader.EndOfStream)
			{
				char c = (char)reader.Read();

				bool endOfRow = false;
				bool endOfItem = false;

				if (c == '"')
				{
					if (!escaped)
					{
						escaped = true;
						if (reader.Peek() == '"')
						{
							reader.Read();
							escaped = false;
						}
					}
					else if (reader.Peek() != '"')
					{
						escaped = false;
					}
					c = (char)reader.Read();
				}

				if (!escaped)
				{
					endOfRow = c == '\r' || c == '\n';
					if (c == '\r' && reader.Peek() == '\n')
					{
						//to prevent empty lines on CLRL
						reader.Read();
					}

					endOfItem = c == ',' || endOfRow;
				}


				if (!endOfItem)
				{
					item.Append(c);
				}
				else
				{
					row.Add(item.ToString());
					item = new StringBuilder();
				}

				if (endOfRow)
				{
					if (!header)
					{
						Add(row);
					}
					else
					{
						header = false;
						Header = row;
					}
					row = new List<string>();
				}
			}
			//last row may be not ended with CRLR
			if (item.Length != 0 && row.Count != 0)
			{
				row.Add(item.ToString());
				Add(row);
			}
		}
	}
}
